package com.ushine.web.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ushine.web.base.mapper.FunctionPermissionMapper;
import com.ushine.web.base.model.relation.RoleAndFunctionPermissionDO;
import com.ushine.web.base.model.system.FunctionPermissionDO;
import com.ushine.web.base.service.IFunctionPermissionService;
import com.ushine.web.base.service.IRoleAndFunPermissionService;
import com.ushine.web.base.service.IUserAndRoleService;
import com.ushine.web.base.util.TreeAssemblyUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author: yls
 * @Date: 2021/3/15 17:24
 * @Description:
 * @Version 1.0
 */
@Service
@Transactional(rollbackFor = {Exception.class})
public class FunctionPermissionServiceImpl extends ServiceImpl<FunctionPermissionMapper, FunctionPermissionDO> implements IFunctionPermissionService {

    @Resource
    private IUserAndRoleService userRoleService;

    @Resource
    private IRoleAndFunPermissionService roleAndPermissionService;

    @Resource
    private TreeAssemblyUtils treeAssemblyUtils;

    @Override
    public Boolean insertPermission(FunctionPermissionDO functionPermissionDO) {
        return save(functionPermissionDO);
    }

    @Override
    public List<FunctionPermissionDO> listPermissonsByRoleIds(Set<Long> roleIds) {
        LambdaQueryWrapper<RoleAndFunctionPermissionDO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(RoleAndFunctionPermissionDO::getRoleId, roleIds);
        List<RoleAndFunctionPermissionDO> rolePermissions = roleAndPermissionService.list(queryWrapper);
        List<Long> permissionIds = rolePermissions.stream().map(RoleAndFunctionPermissionDO::getFunctionPermissionId).collect(Collectors.toList());
        return permissionIds.isEmpty() ? new ArrayList<>() : listByIds(permissionIds);
    }

    @Override
    @Transactional(readOnly = true)
    public List<FunctionPermissionDO> listAllPermissons() {
        List<FunctionPermissionDO> functionPermissionDOList = list();
        return (List<FunctionPermissionDO>) treeAssemblyUtils.getBaseTreeByGroup(functionPermissionDOList);
    }

}
